﻿using System.Runtime.InteropServices;

namespace EventHandlerDemo.Domain.Bases.UOW
{
    public class InnerUnitOfWork : IInnerUnitOfWork
    {
        private readonly IOuterUnitOfWork _parentUnitOfWork;
        private volatile bool _isDisposed;
        private volatile bool _isCompleteCalled;

        public InnerUnitOfWork(IOuterUnitOfWork parentUnitOfWork)
        {
            _parentUnitOfWork = parentUnitOfWork;
        }

        public async Task CompleteAsync()
        {
            await _parentUnitOfWork.SaveChangesAsync();
            _isCompleteCalled = true;
        }

        public void Dispose()
        {
            if (_isDisposed)
            {
                return;
            }

            _isDisposed = true;

            if (!_isCompleteCalled)
            {
                if (HasException())
                {
                    return;
                }

                throw new Exception("");
            }
        }

        private static bool HasException()
        {
            try
            {
                return Marshal.GetExceptionCode() != 0;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}
